package com.eii.resubmit.aop.request.advisor;

import com.eii.resubmit.aop.request.UServlet;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 请求限流工具类
 *
 * @author eii
 * @time 2020/11/28 11:15 下午
 */
public class Util {

    /**
     * 获取key
     */
    public static String servletKey(String sault, HttpServletRequest request) {
        return concat(sault, ":", request.getRequestURI(), ":", UServlet.getAddr(request));
    }
    public static String redisServletKey(String sault, HttpServletRequest request) {
        return DigestUtils.md5Hex(concat(sault, ":", request.getRequestURI(), ":", UServlet.getAddr(request)));
    }
    /**
     * 获取方法全限定名
     */
    public static String fullName(Method method) {
        return concat(method.getDeclaringClass().getCanonicalName(), ".", method.getName());
    }

    /**
     * 批量拼接字符串。<br>
     * 注意:<strong>当输入的字符串数组中某处为null时，会抛出异常.</strong><br>
     */
    public static String concat(String... strings) {
        if (strings == null || strings.length == 0) {
            throw new IllegalArgumentException("it isn't suitable for empty string.");
        }
        int length = strings.length;
        if (length == 1) {
            return strings[0];
        }
        int size = 0;
        for (int i = 0; i < strings.length; i++) {
            // 如果字符串数组某处为null,会自动抛出异常
            size = size + strings[i].length();
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < strings.length; i++) {
            String string = strings[i];
            builder.append(string);
        }
        return builder.toString();
    }

}
